﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Configuration;
using BarFaculdade.Module;
using System.Security;

using Npgsql;

namespace BarFaculdade.DAL
{
   public class UsuarioDAL
   {

       #region Declaração
       string strConn = ConfigurationManager.ConnectionStrings[2].ConnectionString;

       #endregion

       #region Métodos

       public bool conectar(Usuario usuario)
      {

         #region Declaração

          NpgsqlConnection conn;
          NpgsqlCommand cmd;
          string sql = string.Empty;
          NpgsqlDataReader dr;

         #endregion

         #region Implementação

         cmd = new NpgsqlCommand();
         conn = new NpgsqlConnection(strConn);

         try
         {
            sql = "Select id, user, password from login where \"user\" = '" + usuario.User + "';";

            cmd.CommandText = sql;
            cmd.Connection = conn;
            conn.Open();
            dr = cmd.ExecuteReader();

            while (dr.Read())
            {
                string senha = dr["password"].ToString().TrimEnd();
               if (usuario.Senha == dr["password"].ToString().TrimEnd())
               {
                    usuario.ID = dr["id"].ToString();
                  return true;
               }

            }

            return false;
         }
         catch
         {
            return false;
         }
         finally
         {
             conn.Close();
         }

         #endregion
      }


      public bool desconectar()
      {
          #region Declaração
          NpgsqlConnection conn;
          NpgsqlCommand cmd;
          string sql = string.Empty;
          #endregion

          #region Implementação

          cmd = new NpgsqlCommand();
          conn = new NpgsqlConnection(strConn);

          try
          {

              sql = "update login set logado=false;";

              cmd.CommandText = sql;
              cmd.Connection = conn;

              conn.Open();

              cmd.ExecuteNonQuery();

              return true;

          }
          catch
          {
              return false;
          }
          finally
          {
              conn.Close();
          }

          #endregion
      }

      #endregion
   }
}
